<?php
class Member_LoginController extends Zend_Controller_Action
{
	
	function init()
    { 			
        $this->homeUrl = zend_registry::get('config')->default->pages->logedin.'/'.Wmp_Lib::getLocal() ;
    }
	
	public function preDispatch()
    {
        if (Zend_Auth::getInstance()->hasIdentity()) {
            // If the user is logged in, we don't want to show the login form;
            // however, the logout action should still be available
            if ('logout' != $this->getRequest()->getActionName()) {               
            	$this->_redirect($this->homeUrl);
            }
        } else {
            // If they aren't, they can't logout, so that action should
            // redirect to the login form
            if ('logout' == $this->getRequest()->getActionName()) {
                $this->_redirect($this->homeUrl);
            }
        }
    }
    
	public function getAuthAdapter(array $params)
    {
		$authAdapter  = new Zend_Auth_Adapter_DbTable(zend_registry::get('db'));  
		$authAdapter->setTableName('users');  
		$authAdapter->setIdentityColumn('username');  
		$authAdapter->setCredentialColumn('password'); 
		
		$f = new Zend_Filter_StripTags();
		$username = $f->filter($params['username']);
		$password = $f->filter($params['password']);
		 		
		// Set the input credential values to authenticate against 		   
		$authAdapter->setIdentity($username);  		   
		$authAdapter->setCredential(sha1(Zend_registry::get('config')->auth->salt.$password)); 
		
		return $authAdapter;
    }
	
	public function getForm()
    {
        $action_url = $this->view->url(array('module'=>'member', 'controller'=>'login', 'action'=>'process'));
    	$form = new Wmp_Form_LoginForm( array(
				            'action' => $action_url,
				            'method' => 'post',
    						'name' => 'loginform',
    						'id' => 'loginform'
				        ));
    	    	
    	return $form;
    }
    
	public function indexAction()
    {
        //echo "jjj"; exit;
    	$this->view->form = $this->getForm();
    }
    
	public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect(zend_registry::get('config')->default->pages->logedout); // back to login page
    }
    
	public function processAction()
    {
    	$request = $this->getRequest();

        // Check if we have a POST request
        if (!$request->isPost()) {
            return $this->_redirect($this->homeUrl);
        }

        // Get our form and validate it
        $form = $this->getForm();
        if (!$form->isValid($request->getPost())) {
            // Invalid entries
            $this->view->form = $form;
            return $this->render('index'); // re-render the login form
        }

        // Get our authentication adapter and check credentials
        $adapter = $this->getAuthAdapter($form->getValues());
        $auth    = Zend_Auth::getInstance();
      
        $result  = $auth->authenticate($adapter);
        if (!$result->isValid()) {
            // Invalid credentials
            $auth->clearIdentity();
        	
        	$form->setDescription('Invalid credentials provided');
            $this->view->form = $form;
            return $this->render('index');  
        }
		else {
	        // success: store database row to auth's storage 
	        // (Not the password though!)
	        $data = $adapter->getResultRowObject(null,'password');      
	        $auth->getStorage()->write($data);
		}
        
		//We're authenticated! Redirect to the home page,
		//or to the last visited page
    	$userdata = new Zend_Session_Namespace('userdata');
        if(isset($loginRedirect))
        {
        	header("Location: ".$userdata->lastVisitedUrl); 
			exit;        		
        }
        $this->_redirect($this->homeUrl);
    }

	function resetPasswordAction()
	{
		$this->_auth = Zend_Auth::getInstance();
    	if ($this->_auth->hasIdentity())
    		$this->_redirect('/');//OPTIMIZEME: à parametrer (c mieux g pense)
		  	  		
    	$ressetUrl = $this->view->url(
				array('language'=>Wmp_Lib::getLocal(),'module'=>'member', 'controller'=>'login', 'action'=>'reset-password'));
    	$form = new Wmp_Form_ressetPasswordForm(array(
				            'action' => $ressetUrl,
				            'method' => 'post',
				        ));
				            	       
        if ($this->_request->isPost()) {
        	$formData = $this->_request->getPost();        	
            if ($form->isValid($formData)) {
            	//FIXME:send password to user
            } else {
                $this->view->formResponse = 'Sorry, there was a problem with your submission. Please check the following:';
                $form->populate($formData);
            }
        }        
        $this->view->form = $form;		   
	}
}